<?php
use Thenbsp\Wechat\OAuth\Client;
use Thenbsp\Wechat\Wechat\AccessToken;
use Thenbsp\Wechat\Wechat\Jsapi;
use Thenbsp\Wechat\Payment\Unifiedorder;
use Thenbsp\Wechat\Payment\Jsapi\PayRequest;
use Thenbsp\Wechat\Payment\Notify;
use Thenbsp\Wechat\Payment\Query;

class PaymentController extends WechatController {

	const INFO_KEY = 'user:';

	public function indexAction(){
		$config_obj=Yaf_Registry::get("config");
		$config_wechat=$config_obj->wechat->toArray();
		$config_database =$config_obj->database->config->toArray();
		$prefix =$config_database['prefix'];
		$orderTable =new HbModel($prefix.'order');
		$appid =$config_wechat['appid'];
		$appsecret=$config_wechat['appsecret'];
		$mch_id=$config_wechat['mch_id'];
		$wechat_key=$config_wechat['mch_key'];
		$class_accessToken = new AccessToken($appid, $appsecret);		
		$this->redis = RedisDB::factory('wechat');
		$cacheDriver = new \Doctrine\Common\Cache\RedisCache();
		$cacheDriver->setRedis($this->redis);		
		$class_accessToken->setCache($cacheDriver);
		$accessToken = $class_accessToken->getTokenString();
		$jsapi = new Jsapi($class_accessToken);
		$jsapi->setCache($cacheDriver);
		$jsapi->addApi('onMenuShareTimeline')->addApi('onMenuShareAppMessage')->addApi('chooseWXPay');
		$json = $jsapi->getConfig();

		$unifiedorder = new Unifiedorder($appid, $mch_id, $wechat_key);
		// 必填
		//$openid =isset($_COOKIE['openid'])?$_COOKIE['openid']:'';
		$this->mUser = new UserModel(null,false);
		$uid = $this->mUser->getUidByFromuser($this->fromuser);
		if(!$uid){
			$this->response(403,'uid不存在','');
		}
		$this->user = $this->mUser->getInfo();
		$user =$this->user;
		$uid =$user['uid'];
		$level =new LevelModel($uid);
		$levelInfo = $level->getLevel();
		$discount =$levelInfo['discount'];
		$id =intval($_REQUEST['id']);
		if(!$id){
			$result =array('code'=>401,'message'=>'id不能为空.');
			echo json_encode($result);
			exit;
		}
		//从数据库读取
		$goldTable =new HbModel($prefix.'gold_types');
		$sql="SELECT * FROM gm_gold_types WHERE id=".$id." LIMIT 1";
		$res= $goldTable->query($sql);
		if(is_array($res)&&$res){
			foreach ($res as $key => $value) {
				$this_price =$value['price'];
				$gold =$value['gold'];
			}
		}
		$amount = $this_price*100;
		$price =intval($this_price*100*$discount);//乘以折扣
		if(!$gold){
			$result =array('code'=>401,'message'=>'价格错误.');
			echo json_encode($result);
			exit;
		}
		$order_id = date('ymdHis').rand(1000,9999);
		$ip =$this->getip();
		//保存进数据库
		
		$save_post =array(
				'uid'=>$uid,
				'fromuser'=>$this->fromuser,
				'order_id'=>$order_id,
				'created'=>time(),
				'amount'=>$amount,
				'price'=>$price,
				'gold'=>$gold,
				'ip'=>$ip,
			);
		$orderTable->add($save_post);
		$notify_url ="http://".$_SERVER['HTTP_HOST']."/payment/notify_url";
		$unifiedorder->set('body',          '在线账户钻石充值');
		$unifiedorder->set('total_fee',     1);
		$unifiedorder->set('openid',        $this->fromuser);
		$unifiedorder->set('trade_type',    'JSAPI');
		$unifiedorder->set('out_trade_no',  $order_id);
		$unifiedorder->set('notify_url',   $notify_url);		
		$config = new PayRequest($unifiedorder);
		$response = $unifiedorder->getResponse();
		$result =$response->toArray(); 
		if($result['return_code']=="SUCCESS" && $result['return_msg']=='OK'){
			
			$pay_config =array(
				'config'=>json_decode($config),
				'goods_name'=>$gold.'钻('.$gold.'钻石)',
				'pay_price'=>$price/100,
				'nickname'=>$user['nickname'],
				'order_id'=>$order_id,
			);
			$this->response(200,'支付信息',$pay_config);
			
		}else{			
			$this->response(501,$result,'');
		}

			//exit;
		    
		//$this->view->assign('parameters', $config);
	}
	public function notify_urlAction(){
		$config_obj=Yaf_Registry::get("config");
		$config_wechat=$config_obj->wechat->toArray();
		$config_database =$config_obj->database->config->toArray();
		$prefix =$config_database['prefix'];
		$orderTable =new HbModel($prefix.'order');
		$appid =$config_wechat['appid'];
		$appsecret=$config_wechat['appsecret'];
		$mch_id=$config_wechat['mch_id'];
		$wechat_key=$config_wechat['mch_key'];

		$query =new Query($appid,$mch_id,$wechat_key);
		$order_id = $_GET['order_id'];
		//file_put_contents('order.txt',$order_id.PHP_EOL,FILE_APPEND);
		if($order_id){
			$result=$query->fromOutTradeNo($order_id);
			if($result['return_code']=="SUCCESS"){
				if($result['trade_state']=="SUCCESS"){
					//成功交易
					$orderTable =new HbModel($prefix.'order');
					//update
					$pay_time =time();
					$sql ="UPDATE gm_order SET is_pay=2,pay_time=".$pay_time."  WHERE order_id='".$order_id."'";
					$orderTable->query($sql);
					//redis 更新钻石
					$select_sql ="SELECT * FROM gm_order WHERE order_id='".$order_id."' LIMIT 1";
					$result_db =$orderTable->query($select_sql);
					$result_db =isset($result_db[0])?$result_db[0]:'';
					$uid =$result_db['uid'];
					$gold =$result_db['gold'];
					$this->redis = RedisDB::factory('user');
					$userinfo = $this->redis->hGetAll(self::INFO_KEY . $uid);
					$org_gold =$userinfo['gold'];
					$now_gold =$org_gold+$gold;
					$userinfo['gold']=$now_gold;
					$this->redis->hMSet(self::INFO_KEY . $uid,$userinfo);

				}
			}
			
		}

		//$notify = new Notify();
		// if($notify->containsKey('out_trade_no') ) {
		//     // 失败时必需返回，否则微信服务器将重复提交通知
		//     $notify->fail('Invalid Request');
		// }
		
		
		
	}	
}